package com.lbj.mvvm.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.lbj.mvvm.helper.VMFactory
import com.lbj.mvvm.helper.getVMClazz

abstract class JetpackVMFragment<VM : JetpackVM> : Fragment() {

    lateinit var VM: VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        VM = ViewModelProvider(this, VMFactory()).get(getVMClazz(this) as Class<VM>)
        initStart()
    }

    abstract fun layoutId(): Int
    abstract fun initStart()
    abstract fun showLoading(message: String = "请求网络中...")
    abstract fun dismissLoading()

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        VM.defUI.showDialog.observe(viewLifecycleOwner, Observer {
            showLoading()
        })
        VM.defUI.dismissDialog.observe(viewLifecycleOwner, Observer {
            dismissLoading()
        })
    }
}